package com.abl.common.scheduled;


import com.abl.core.domain.db.MtRoomApply;
import com.abl.core.domain.db.SysUser;
import com.abl.core.mybatis.mapper.MtRoomApplyMapper;
import com.abl.core.mybatis.mapper.SysUserMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Row;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.abl.core.domain.po.table.MtRoomApplyTableDef.MT_ROOM_APPLY;
import static com.abl.core.domain.po.table.SysUserTableDef.SYS_USER;
import static com.mybatisflex.core.query.QueryMethods.max;
import static com.mybatisflex.core.query.QueryMethods.now;

/**
 * @author leyili
 * @since 2023-10-03 10:59:41
 */
@Slf4j
@Component
public class SysUserTask {

    @Resource
    MtRoomApplyMapper mtRoomApplyMapper;

    @Resource
    SysUserMapper sysUserMapper;

    /**
     * 定时清理 开会权限 
     */
    @Scheduled(cron = "0 * * * * ?")
    public void scheduledMethod() {
        QueryWrapper wrapper = new QueryWrapper();

        // 查询所有到期还有权限的
        wrapper.select(MT_ROOM_APPLY.USER_ID, max(MT_ROOM_APPLY.APPLY_CLOSE_TIME).as("applyCloseTime"))
                .from(MtRoomApply.class)
                .leftJoin(SysUser.class)
                .on(MT_ROOM_APPLY.USER_ID.eq(SYS_USER.ID))
                .and(MT_ROOM_APPLY.APPLY_STATUS.eq("1"))
                .and(SYS_USER.MT_AUTH.eq("1"))
                .groupBy(MT_ROOM_APPLY.USER_ID)
                .having(max(MT_ROOM_APPLY.APPLY_CLOSE_TIME).lt(now()));
        List<Row> result = mtRoomApplyMapper.selectListByQueryAs(wrapper, Row.class);
        // 修改user表
        for (Row row : result) {
            // 通过 Row 对象访问查询结果
            String userId = row.getString("userId");
            SysUser sysUser = new SysUser();
            sysUser.setId(userId);
            sysUser.setMtAuth("0");
            sysUserMapper.update(sysUser);
            log.info("定时清理开会权限到期用户-ID:{}", userId);
        }

    }

}
